package com.cyurs.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/11/16
 */
public class ScatterAndGatherDemo {
    public static void main(String[] args) throws Exception {
        //开启服务器SocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7777);
        serverSocketChannel.socket().bind(inetSocketAddress); //绑定端口
        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5); //支持5个字节
        byteBuffers[1] = ByteBuffer.allocate(3); //支持3个字节
        //等待客户端进行连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        int messageLength = 8; //Buffer最大支持字节数
        //循环读取
        while (true) {
            int byteRead = 0;
            while (byteRead < messageLength) {
                //将通道数据读到缓冲区buffer数组中
                long l = socketChannel.read(byteBuffers);
                byteRead += l;
                System.out.println("byteRead=" + byteRead);
                Arrays.asList(byteBuffers).stream().map(buffer -> "position=" +
                        buffer.position() + ", limit=" + buffer.limit()).forEach(System.out::println);
            }
            //将所有buffer进行flip读写切换
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.flip());
            //将数据从buffer数组中读取出来
            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;

            }
            //将所有buffer进行clear 复位
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear());
            System.out.println("byteRead:="+byteRead+"   byteWrite="+byteWrite+"   messageLength="+messageLength);
        }
    }
}
